from app.models import Product, DictData
from app import db
from exts import JsonConverter, BeanUtils


def product_add(product):
    '''
    添加产品
    :param product:
    :return:
    '''
    o = JsonConverter.dict_to_object(product, Product)
    db.session.add(o)
    db.session.commit()


def product_update(product):
    '''
    更新产品
    :param product:
    :return:
    '''
    '''
    :param news:
    :return:
    '''
    o = Product.query.get(product['id'])
    # 对象复制
    BeanUtils.copy(product, o)
    db.session.commit()


def product_delete(id):
    '''
    删除产品
    :param id:
    :return:
    '''
    o = Product.query.get(id)
    db.session.delete(o)
    db.session.commit()


def product_detail(id):
    '''
    查询产品方案
    :param id:
    :return:
    '''
    return Product.query.get(id)


def product_get_by_id(id):
    '''
    查询产品方案
    :param id:
    :return:
    '''
    return Product.query.get(id)


def product_page(pageNum, pageSize):
    '''
    分页查询产品
    :param params:
    :return:
    '''
    return Product.query.paginate(page=pageNum, per_page=pageSize)


def product_all():
    '''
    查询所有产品
    :return:
    '''
    return Product.query.all()


def product_tree():
    '''
    树形查询
    :return:
    '''
    product_type_list = DictData.query.filter_by(dict_type='product_type').all()
    tree = []
    for product_type in product_type_list:
        node = {
            'first_type_code': product_type.dict_value,
            'first_type_name': product_type.dict_label,
            'products': []
        }
        products = Product.query.filter_by(product_type_code=product_type.dict_value).all()
        for product in products:
            node['products'].append({
                'id': product.id,
                'type': product.type,
                'product_name': product.product_name,
                'image': product.image,
                'introduce': product.introduce,
                'create_time': product.create_time,
                'update_time': product.update_time
            })
        tree.append(node)

    return tree
